/*
 Copyright 2008 Jason E. Smith Licensed under the Apache License, Version 2.0 (the "License");
 You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 */
new Class("js::ActiveModel", {
    inherits: js.Model,
	validateOnSave 	 : true,
	validateOnCreate : true,
	root : "",
	
    dispose: function(){
        if (!this.get("id")) {
            throw new Error("The " + this.classname.toLowerCase() + " has no id. It is most likely not saved yet.");
            return;
        }
        /*var myRequest = new Request.JSON({
            url: "/" + this.classname.toLowerCase().pluralize() + "/" + this.get("id"),
            method: 'DELETE',
            onSuccess: function(r){
                console.log(">> The " + this.classname.toLowerCase() + " was successfully destroyed")
                this.update(r ||{});
                this.triggerEvent("onDisposed", this);
            }.bind(this),
            onFailure: function(r){
                console.log(r)
            }.bind(this)
        })
        myRequest.setHeader('Content-Type', "application/x-www-form-urlencoded");
        myRequest.send();*/
		
    },
	
    create: function(){
        var klass = this.constructor;
		var classname = this.classname;
		var that = this;
		var url  = "/" + this.classname.toLowerCase().pluralize() + ".json";
		var xhr  = new http.XHR(20000,2);
			xhr.onreadystateloaded = function(){
               that.update(JSON.parse(this.req.responseText) || {});
			};
			xhr.open('POST', url, true);
			xhr.setRequestHeader('Content-Type', "application/json");																			
			xhr.send(this.toJSON());

        /*var myRequest = new Request.JSON({
            url: "/" + this.classname.toLowerCase().pluralize(),
            method: 'POST',
            onSuccess: function(r){
                console.log(">> New " + this.classname.toLowerCase() + " successfully created")
                this.update(r ||{});
                this.triggerEvent("onCreated", this);
            }.bind(this),
            onFailure: function(r){
                console.log(r)
            }.bind(this)
        })
        	
        myRequest.send(this.toJSON());*/
		
    },
	
    save : function(){
		if(!this.validate(true)) return;
        var id = this.get("id");
		var errors = (this.validateOnSave)? this.validate():null;
		if(errors.length) {
			throw new Error(errors);
			return false;
		}
        if (!id) {
            this.triggerEvent("onBeforeCreate", this);
            this.create();
        }
        else {
            this.update(null, true);
            this.triggerEvent("onAfterCreate", this);
        }
    },
	
    update: function(args, force){
        var klass = this.constructor;
        if (args) Object.extend(this.getModel(), args);
        if (typeof(force) == "undefined" || force == (false || null)) 
            return this;
        if (!this.get("id")) {
            throw new Error("The " + this.classname.toLowerCase() + " has no id. It is most likely not saved yet.");
            return this;
        }
       /* var updateRequest = new Request.JSON({
            url: "/" + this.classname.toLowerCase().pluralize() + "/" + this.get("id"),
            method: 'PUT',
            onSuccess: function(r){
                var res = JSON.decode(updateRequest.xhr.responseText);
                Object.extend(this.getModel(), res);
                this.triggerEvent("onUpdated", this);
            }.bind(this),
            onFailure: function(f){
                console.log(f)
            }
        })
        updateRequest.setHeader('Content-Type', "application/json");
        updateRequest.send(this.toJSON());*/
    }
});

	js.ActiveModel.find = function(_id, f){
	    var callback = f;
	    var klass = this;
		var url = "/" + this.prototype.classname.toLowerCase().pluralize() + "/" + _id;
	    /*var findRequest = new Request.JSON({
	        url: "/" + this.prototype.classname.toLowerCase().pluralize() + "/" + _id,
	        method: 'GET',
	        onSuccess: function(r){
				var res = klass.fromJSON(findRequest.xhr.responseText);
	            callback(res);
	            this.triggerEvent("onResult", res);
	        },
	        onFailure: function(f){
	            console.log(f)
	        }
	    })*/
		DOMAssistant.AJAX.get(url + ".json", function(res){
			var obj = klass.fromJSON(res);
	        callback(obj);
		});
//	    findRequest.setHeader('Content-Type', "application/json");
//	    findRequest.send();
	    return this;
	}
	
	js.ActiveModel.findAll = function(f){
	    var callback = f;
	    var klass = this;
	    var results = [];
		var url = "/" + this.prototype.classname.toLowerCase().pluralize();
	    /*var findAllRequest = new Request.JSON({
	        url: "/" + this.prototype.classname.toLowerCase().pluralize(),
	        method: 'GET',
	        onSuccess: function(r){
				var res = klass.fromJSON(findAllRequest.xhr.responseText);
	            callback(res);
	            //this.triggerEvent("result", this);
	        }.bind(this),
	        onFailure: function(f){
	            console.log(f)
	        }
	    });
	    findAllRequest.setHeader("Content-Type", "application/json");
	    findAllRequest.send();*/
		DOMAssistant.AJAX.get(url + ".json", function(res){
			var list = klass.fromJSON(res);
	        callback(list);
		})
		return this;
	}
	
	js.ActiveModel.create = function(o, callback){
		var klass = this;
		if(typeof callback != "function") {
			throw new TypeError("Pass a callback function to " + klass.prototype.classname + ".create() to get the newly created " + klass.prototype.classname.toLowerCase());
		}
		var o = new klass(o);
		if(!o.validate()) {return false}
        var myRequest = new Request.JSON({
            url: "/" + klass.prototype.classname.toLowerCase().pluralize(),
            method: 'POST',
            onSuccess: function(r){
				o.update(r || {});
				if(callback) callback(o);},
            onFailure: function(r){throw new Error(r)}
        })
        myRequest.setHeader('Content-Type', "application/json");
        myRequest.send(o.toJSON());
    }
